package com.bangcommunity.bbframe.fdfs;

import com.bangcommunity.bbframe.fdfs.config.FdfsClientConfig;
import com.bangcommunity.bbframe.fdfs.connection.StorageConnection;
import com.bangcommunity.bbframe.fdfs.connection.StorageConnectionFactory;
import com.bangcommunity.bbframe.fdfs.connection.TrackerConnection;
import com.bangcommunity.bbframe.fdfs.connection.TrackerConnectionFactory;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.TrackerGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FdfsClientUtil {

    private static Logger logger = LoggerFactory.getLogger(FdfsClientUtil.class);
	
	private static volatile FdfsClient fastdfsClient;
    private static FdfsClientConfig config = null;

    private final static String configFile = "fdfs_client.properties";

    public FdfsClientUtil() {
    }

    public static FdfsClient getFdfsClient(){
        if (fastdfsClient == null) {
            synchronized (FdfsClient.class) {
                if (fastdfsClient == null) {
                    try {
                        config = new FdfsClientConfig(configFile);
                    } catch (ConfigurationException e) {
                        logger.warn("Load fastdfs config failed.",e);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    TrackerConnectionFactory trackerConnectionFactory = new TrackerConnectionFactory(config);
                    StorageConnectionFactory storageConnectionFactory = new StorageConnectionFactory(config);
                    GenericKeyedObjectPool<String,TrackerConnection> trackerClientPool = new GenericKeyedObjectPool<>(trackerConnectionFactory,trackerConnectionFactory.getClientPoolConfig());
                    GenericKeyedObjectPool<StorageAddress,StorageConnection> storageClientPool = new GenericKeyedObjectPool<>(storageConnectionFactory,storageConnectionFactory.getClientPoolConfig());
                    TrackerGroup g_tracker_group = ClientGlobal.g_tracker_group;
                    fastdfsClient = new FdfsClientImpl(g_tracker_group,trackerClientPool,storageClientPool);
                }
            }
        }
        return fastdfsClient;
    }
    public static String[] splitFileId(String fullFileId) {
        int pos = fullFileId.indexOf(FdfsClient.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR);
        if ((pos <= 0) || (pos == fullFileId.length() - 1)) {
            throw new RuntimeException("invalid fullfileId");
        }
        return new String[] { fullFileId.substring(0, pos), fullFileId.substring(pos + 1) };
    }



}
